import { onMounted, onUnmounted, ref } from "vue";

export function useScroll() {
  const pageNum = ref(1);

  const timeout = ref();
  const stopFlag = ref(false);

  const stop = (flag: boolean) => {
    stopFlag.value = flag;
  };
  const handleScroll = () => {
    if (stopFlag.value) return;
    if (
      document.documentElement.scrollTop +
        document.documentElement.clientHeight >=
      document.documentElement.scrollHeight
    ) {
      console.log("触底了" + pageNum.value);
      if (!timeout.value) {
        timeout.value = setTimeout(() => {
          pageNum.value = pageNum.value + 1;
          timeout.value = null;
        }, 1000);
      }
    }
  };

  onMounted(() => {
    document.addEventListener("scroll", handleScroll, true);
  });
  onUnmounted(() => {
    document.removeEventListener("scroll", handleScroll, true);
  });
  return { pageNum, stop };
}
